package com.jinlejia.erp.widget.musicView;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.jinlejia.erp.R;

/**
 * Created by Administrator on 2017/8/16 0016.
 */

public class MusicView extends LinearLayout implements MediaService.IMediaStateListener, ServiceConnection {
    private final String TAG = "MusicView";
    private Context mContext;
    private ImageView playBtn;
    private SeekBar seekBar;
    private TextView timeView;

    private String mCurPlayUrl;
    private boolean mIsPlay;
    private boolean mIsPlayComplete;
    private boolean mIsPause;

    private MediaService mediaService;
    private OnMusicStateListener mMusicStateListener;
    private HeadsetPlugReceiver mHeadsetPlugReceiver;
    private OnControlClickListener mControlClickListener;

    private int musicDuration;

    private String showMusicDuration;

    public MusicView(Context context) {
        this(context, null);
    }

    public MusicView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MusicView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        initView();
        mIsPlay = false;
        mIsPlayComplete = false;
        mIsPause = false;
    }

    private void initView() {
        initReceiver();
        View view = View.inflate(mContext, R.layout.music_view_layout, this);
        playBtn = (ImageView) view.findViewById(R.id.btn);
        seekBar = (SeekBar) view.findViewById(R.id.seek);
        timeView = (TextView) view.findViewById(R.id.time);
        playBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != mControlClickListener) {
                    mControlClickListener.onClick();
                }
            }
        });

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            int mProgress;

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                Log.d("mediaPlayer111111", "seekTO : " + progress);
                mProgress = progress * musicDuration
                        / seekBar.getMax();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                seekToMusic(mProgress);
            }
        });

    }

    public void reset() {
        seekBar.setProgress(0);
        timeView.setText("");
        mIsPlay = false;
        mIsPlayComplete = false;
        mIsPause = false;
        changeControlBtnState(false);
    }

    /**
     * 播放地址
     *
     * @param url
     */
    public void setPlayUrl(String url) {
        this.mCurPlayUrl = url;
    }

    private void initReceiver() {
        if (mHeadsetPlugReceiver == null) {
            mHeadsetPlugReceiver = new HeadsetPlugReceiver();
        }
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
        mContext.registerReceiver(mHeadsetPlugReceiver, intentFilter);
    }

    public void controlBtnClick() {
        if (!mIsPause && !mIsPlay && !mIsPlayComplete) {
            startPlayMusic();
            changeControlBtnState(true);
        } else if (isPlaying()) {
            pausePlayMusic();
            changeControlBtnState(false);
        } else if (mIsPlayComplete) {
            startPlayMusic();
            seekBar.setProgress(0);
            mIsPlayComplete = false;
            changeControlBtnState(true);
        } else if (mIsPause) {
            if (mediaService != null) {
                mediaService.paly();
                changeControlBtnState(true);
            }
        }

        Log.i(TAG, "controlBtnClick: isPlay=" + mIsPlay);
    }

    public void startPlayMusic() {
        changeControlBtnState(true);
        if (mediaService == null) {
            // bind service
            Intent intent = new Intent(mContext, MediaService.class);
            mContext.bindService(intent, MusicView.this, Context.BIND_AUTO_CREATE);
        } else {
            mediaService.playMusic(mCurPlayUrl);
        }
        Log.d(TAG, "startPlayMusic: [ " + mCurPlayUrl + " ]");
    }

    public void resumePlayMusic() {
        if (mediaService != null) {
            mediaService.resumeMusic(mCurPlayUrl);
        }
        Log.d(TAG, "resumePlayMusic: [ " + this.hashCode() + " ]");
    }

    public void pausePlayMusic() {
        mIsPause = true;
        if (mediaService != null) {
            mediaService.pauseMusic();
        }
        Log.d(TAG, "pausePlayMusic: [ " + this.hashCode() + " ]");
    }

    public void seekToMusic(int pos) {
        if (mediaService != null) {
            mediaService.seekToMusic(pos);
        }
        Log.d(TAG, "seekToMusic: pos = " + pos);
    }

    public void stopPlayMusic() {
        mContext.unbindService(MusicView.this);
        if (mHeadsetPlugReceiver != null) {
            mContext.unregisterReceiver(mHeadsetPlugReceiver);
        }
        mContext = null;
        Log.d(TAG, "stopPlayMusic: [ " + hashCode() + " ]");
    }


    public boolean isPlaying() {
        return mIsPlay;
    }

    public void changeControlBtnState(boolean isPlay) {
        if (isPlay) {
            playBtn.setImageResource(R.mipmap.ic_pause);
            mIsPlay = true;
        } else {
            playBtn.setImageResource(R.mipmap.ic_play);
            mIsPlay = false;
        }
    }

    public void setOnMusicStateListener(OnMusicStateListener listener) {
        mMusicStateListener = listener;
    }

    @Override
    public void onPrepared(int duration) {
        Log.d(TAG, "onPrepared: STATE_MUSIC_PREPARE");
        musicDuration = duration;
        int musicTime = duration / 1000;
        showMusicDuration = musicTime / 60 + ":" + musicTime % 60;
        timeView.setText(showMusicDuration+"/"+showMusicDuration);
    }

    @Override
    public void onProgressUpdate(int currentPos, int duration) {
        int musicTime = currentPos / 1000;
        String show = musicTime / 60 + ":" + musicTime % 60;
        timeView.setText(show+"/"+showMusicDuration);
        if (duration > 0) {
            long pos = seekBar.getMax() * currentPos / duration;
            seekBar.setProgress((int) pos);
        }
    }

    @Override
    public void onBufferingUpdate(int bufferingProgress) {
        seekBar.setSecondaryProgress(bufferingProgress);
    }

    @Override
    public void onSeekComplete() {
        Log.d(TAG, "onSeekComplete: STATE_SEEK_COMPLETE");
    }

    @Override
    public void onCompletion() {
        mIsPlayComplete = true;
        changeControlBtnState(false);
        if (mMusicStateListener != null) {
            mMusicStateListener.onMusicPlayComplete();
        }
        Log.d(TAG, "onCompletion: STATE_PLAY_COMPLETE");
    }

    @Override
    public boolean onInfo(int what, int extra) {
        Log.d(TAG, "oninfo" + what + "   " + extra);
        if (what == MediaPlayer.MEDIA_INFO_BUFFERING_START) {
            Log.i(TAG, "MEDIA_INFO_BUFFERING_START");
        } else if (what == MediaPlayer.MEDIA_INFO_BUFFERING_END) {
            Log.i(TAG, "MEDIA_INFO_BUFFERING_END");
        }
        return false;
    }

    @Override
    public boolean onError(int what, int extra) {
        changeControlBtnState(false);
        Log.d(TAG, "onError: STATE_PLAY_ERROR");
        return false;
    }

    public interface OnMusicStateListener {
        void onPrepared(int duration);

        void onError(int what, int extra);

        void onInfo(int what, int extra);

        void onMusicPlayComplete();

        void onSeekComplete();

        void onProgressUpdate(int duration, int currentPos);

        void onHeadsetPullOut();
    }

    public interface OnControlClickListener {
        void onClick();
    }

    public void setOnControlClickListener(OnControlClickListener listener) {
        this.mControlClickListener = listener;
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        Log.i(TAG, "onServiceConnected: [ " + this.hashCode() + " ]");
        MediaService.MediaBinder mediaBinder = (MediaService.MediaBinder) service;
        mediaService = mediaBinder.getService();
        mediaService.setMediaStateListener(MusicView.this);
        if (!TextUtils.isEmpty(mCurPlayUrl) && mediaService != null) {
            mediaService.playMusic(mCurPlayUrl);
        }
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
    }

    private class HeadsetPlugReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals(action)) {
                if (mIsPlay) {
                    if (mMusicStateListener != null) {
                        mMusicStateListener.onHeadsetPullOut();
                    }
                    pausePlayMusic();
                    changeControlBtnState(false);
                }
            }
            Log.d(TAG, "onReceive: ===HeadsetPullout===");
        }
    }

}
